import './assets/main.css'
import "@/assets/styles/index.scss";

import {createApp} from 'vue'
import {createPinia} from 'pinia'
import App from './App.vue'
import router from './router'
import createCache from "@/stores/cache";

import 'virtual:svg-icons-register'
import plugins from '@/plugins'

import ElementPlus from 'element-plus';
import 'element-plus/dist/index.css'

import * as epIconsVue from '@element-plus/icons-vue'
import {useStore} from "@/stores";
import {executeLoginByCode} from "@/utils/LoginUtil";

const app = createApp(App)
for (const [key, component] of Object.entries(epIconsVue)) {
    app.component(key, component)
}

const sessionCache = createCache({mode: 'session'});

app.use(createCache())
app.use(sessionCache)

app.use(ElementPlus)
app.use(createPinia())
app.use(router)
app.use(plugins)

const clientId = import.meta.env.VITE_APP_CLIENT_ID;
const clientSecret = import.meta.env.VITE_APP_CLIENT_SECRET;
const platform = import.meta.env.VITE_APP_PLATFORM;
const ssoLoginUrl = import.meta.env.VITE_APP_SSO_LOGIN_URL;

async function initSso() {
    const params = new URLSearchParams(window.location.search);
    const code = params.get('code') || '';
    const store = useStore();
    const cred = store.getCredential();

    if (cred && cred.cred) {
        app.mount('#app')
    } else if (!code) {
        // 转到统一单点登录
        window.location.href=`${ssoLoginUrl}/?platform=${platform}&client_id=${clientId}&client_secret=${clientSecret}`
    } else {
        // 从后台获取Token，完成登录
        await executeLoginByCode(code, '/dashboard');
        await router.push({
            path: '/dashboard'
        })
        app.mount('#app')
    }
}

initSso().then(r => console.log(r));
